<template>
  <div class="auth-content">
    <!--展示权限详情-->
    <div class="flex" style="width: 100%" v-if="authMsgInfo.parentId !== ''">
      <div style="flex: 1; margin-right: 10px">
        <dt-info ref="msgRef"></dt-info>
      </div>
      <div class="flex">
        <Button type="success" style="margin-left: 8px" @click="saveFun">保存</Button>
        <Button @click="delFun" style="margin-left: 8px" v-if="!subFlag">删除</Button>
        <Button style="margin-left: 8px" v-if="subFlag" @click="cancelFun">取消</Button>
        <Button
          type="primary"
          style="margin-left: 8px"
          @click="createSubAuth"
          v-if="authMsgInfo.menuLevel < 5 && !subFlag">
          创建子权限
        </Button>
      </div>
    </div>
    <Row ref="contentHeight" class="flex flex-horizontal-between tree-content">
      <Col span="6" style="border-right: 1px solid #999; height: 100%">
        <div style="height: 100%">
          <p class="title-text">权限菜单</p>
          <div class="tree">
            <Tree :data="permissionData" ref="treeRef" @on-select-change="treeSelectChange"></Tree>
          </div>
        </div>
      </Col>
      <Col span="15" style="height: 100%">
        <div style="height: 100%">
          <p class="title-text">后台菜单</p>
          <div class="tree">
            <Tree
              :data="webData"
              ref="backTreeRef"
              show-checkbox
              check-strictly
              check-directly
              @on-check-change="webChange"></Tree>
          </div>
        </div>
      </Col>
      <!-- <Col span="5" style="height: 100%">
        <div style="height: 100%">
          <p class="title-text">小程序菜单</p>
          <div class="tree">
            <Tree
              :data="minAppData"
              ref="smlTreeRef"
              show-checkbox
              check-strictly
              check-directly
              @on-check-change="minAppChange"></Tree>
          </div>
        </div>
      </Col>
      <Col span="5" style="height: 100%">
        <div style="height: 100%">
          <p class="title-text">APP菜单</p>
          <div class="tree">
            <Tree
              :data="appData"
              ref="appTreeRef"
              show-checkbox
              check-strictly
              check-directly
              @on-check-change="appChange"></Tree>
          </div>
        </div>
      </Col> -->
    </Row>
    <dt-loading ref="loadingRef" :loading="loading"></dt-loading>
  </div>
</template>

<script setup>
  import { onMounted, reactive, ref, nextTick } from 'vue'
  import { msgOpt } from './biz/msg'
  import { subMsgOpt } from './biz/subMsg'
  import dt from '@dt/dt'
  import authMgr from './biz/index'
  import permissionMgr from '@/biz/permission'

  const [treeRef, msgRef, backTreeRef, smlTreeRef, appTreeRef] = [ref(), ref(), ref(), ref(), ref()]
  const loading = ref(false)

  const authMsgInfo = reactive({
    parentId: '',
    id: '',
    menuLevel: '',
    title: '',
    childNum: 0
  })

  const authSubInfo = reactive({
    parentId: '',
    title: ''
  })

  const permissionData = ref([])
  const webData = ref([])
  const minAppData = ref([])
  const appData = ref([])
  const subFlag = ref(false)
  const minAppList = ref([])
  const webList = ref([])
  const appList = ref([])

  onMounted(() => {
    getPermissionData()
    // 三类菜单
    Promise.all([getSysMenuListWeb(), getSysMenuListMinApp(), getSysMenuListApp()])
      .then(() => {
        loading.value = false
      })
      .catch(() => {
        loading.value = false
      })
  })

  function getPermissionData() {
    loading.value = true
    // 权限树数据
    return permissionMgr.permissionMenuList().then((res) => {
      permissionData.value = res
    })
  }

  function getSysMenuListWeb() {
    let params = {
      menuItem: '1'
    }
    // 后台菜单
    return permissionMgr.sysMenuList(params).then((res) => {
      webData.value = res
    })
  }

  function getSysMenuListMinApp() {
    Promise.resolve(true)
  }

  function getSysMenuListApp() {
    Promise.resolve(true)
  }

  function treeSelectChange(val) {
    subFlag.value = false
    if (val.length != 0) {
      let checkNode = val[0]
      authMsgInfo.id = checkNode.id
      authMsgInfo.parentId = checkNode.menuLevel == 0 ? '无上级权限ID' : checkNode.parentId
      authMsgInfo.title = checkNode.title
      authMsgInfo.menuLevel = checkNode.menuLevel.toString()
      authMsgInfo.childNum = checkNode.children.length

      nextTick(() => {
        msgRef.value.init(new msgOpt(), authMsgInfo)
      })
      getPermissionMenuFun()
    } else {
      authMsgInfo.parentId = ''
      clearMenuCheck()
    }
  }

  // 权限对应的菜单
  function getPermissionMenuFun() {
    let params = {
      id: authMsgInfo.id
    }
    authMgr.getBindSysMenuById(params).then((res) => {
      webList.value = dt.tool.deepClone(res.webMenuIds)
      minAppList.value = dt.tool.deepClone(res.minAppMenuIds)
      appList.value = dt.tool.deepClone(res.appMenuIds)
      resolveTree(webData.value, res.webMenuIds)
      resolveTree(minAppData.value, res.minAppMenuIds)
      resolveTree(appData.value, res.appMenuIds)
    })
  }

  // 清空菜单选择
  function clearMenuCheck() {
    webList.value = []
    minAppList.value = []
    appList.value = []
    resolveTree(webData.value, [])
    resolveTree(minAppData.value, [])
    resolveTree(appData.value, [])
    loading.value = false
  }

  function createSubAuth() {
    if (authMsgInfo.childNum >= 99) {
      dt.ui.Message.info('每级至多可添加99个“权限”')
      return false
    }

    subFlag.value = true

    authSubInfo.id = authMsgInfo.id
    authSubInfo.title = ''

    msgRef.value.init(new subMsgOpt(), authSubInfo)
  }

  function saveFun() {
    msgRef.value.validate().then((res) => {
      if (res) {
        if (subFlag.value) {
          // 子权限
          let params = {
            ...authSubInfo
          }
          authMgr.permissionMenuSave(params).then((res) => {
            getPermissionData()
            clearMenuCheck()
            dt.ui.Message.success('子权限创建成功')
            subFlag.value = false
            authMsgInfo.parentId = ''
          })
        } else {
          let params = {
            ...authMsgInfo
          }
          authMgr.permissionMenuUpdate(params).then((res) => {
            permissionBindFun()
          })
        }
      }
    })
  }

  // 权限绑定
  function permissionBindFun() {
    let params = {
      id: authMsgInfo.id, //#权限id
      webMenuList: webList.value, //#后台菜单id集合
      minAppMenuList: minAppList.value, //#小程序菜单id集合
      appMenuList: appList.value //#APP菜单id集合
    }
    authMgr.permissionMenuBind(params).then(async (res) => {
      dt.ui.Message.success('权限保存成功')
      await getPermissionData()
      deafultCheckTree(permissionData.value, authMsgInfo.id)
      loading.value = false
    })
  }

  function delFun() {
    dt.ui.Modal.confirm({
      title: '删除权限',
      content: `确定删除权限 "${authMsgInfo.title}" ?`,
      onOk: () => {
        authMgr.permissionMenuDelete(authMsgInfo.id).then((res) => {
          dt.ui.Message.success('权限删除成功')
          subFlag.value = false
          authMsgInfo.parentId = ''
          getPermissionData()
          clearMenuCheck()
        })
      },
      onCancel: () => {
        dt.ui.Message.info('您取消了操作。')
      }
    })
  }

  function cancelFun() {
    subFlag.value = false
    msgRef.value.resetFields()
    msgRef.value.init(new msgOpt(), authMsgInfo)
  }

  function webChange(val, target) {
    webList.value = []
    dt.tool.treeChange(webData.value, target, backTreeRef.value).then((res) => {
      console.log('zhk ~ file: index.vue:281 ~ treeChange ~ res:', res)
      res.forEach((item) => {
        webList.value.push(item.id)
      })
    })
  }

  function minAppChange(val) {
    minAppList.value = []
    val.forEach((item) => {
      minAppList.value.push(item.id)
    })
  }

  function appChange(val) {
    appList.value = []
    val.forEach((item) => {
      appList.value.push(item.id)
    })
  }

  function resolveTree(treeData, ids) {
    treeData.forEach((item) => {
      if (ids.includes(Number(item.id))) {
        item.checked = true
      } else {
        item.checked = false
      }
      if (item.children && item.children.length > 0) {
        resolveTree(item.children, ids)
      }
    })
  }
  function deafultCheckTree(treeData, id) {
    treeData.forEach((item) => {
      if (id == item.id) {
        item.selected = true
      } else {
        item.selected = false
      }
      if (item.children && item.children.length > 0) {
        deafultCheckTree(item.children, id)
      }
    })
  }
</script>

<style lang="scss" scoped>
  .auth-content {
    height: 100%;
    .tree-content {
      height: calc(100% - 60px);
      .title-text {
        margin-bottom: 20px;
        font-size: 18px;
        color: #333;
        font-weight: bold;
      }
    }
    .tree {
      max-height: calc(100% - 30px);
      overflow-y: auto;
      overflow-x: hidden;
    }
  }
  .tree::-webkit-scrollbar {
    width: 0 !important;
  }

  .tree::-webkit-scrollbar {
    width: 0 !important;
    height: 0;
  }
</style>
